#include "food.h"
#include <QRandomGenerator>

Food::Food(int gameWidth, int gameHeight, int stepSize, QObject *parent) :
    QObject(parent),
    m_gameWidth(gameWidth),
    m_gameHeight(gameHeight),
    m_stepSize(stepSize)
{
    // 初始生成食物
    generateNew(QList<QPoint>());
}

void Food::generateNew(const QList<QPoint> &snakeBody)
{
    bool validPosition = false;
    
    // 生成有效的食物位置（不与蛇身重叠）
    while (!validPosition) {
        // 随机生成位置（确保是步长的整数倍）
        int x = QRandomGenerator::global()->bounded(m_gameWidth / m_stepSize) * m_stepSize;
        int y = QRandomGenerator::global()->bounded(m_gameHeight / m_stepSize) * m_stepSize;
        m_position = QPoint(x, y);
        
        // 检查是否与蛇身重叠
        validPosition = !snakeBody.contains(m_position);
    }
}
